package order

import (
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go-papers/constant"

	"go-papers/models"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

// DownOrderList
func DownOrderList(c *gin.Context) {
	var data models.Order
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	data.OrderNo = c.Request.FormValue("orderNo")
	data.OrderName = c.Request.FormValue("orderName")
	data.OrderStatus = c.Request.FormValue("orderStatus")

	if index := c.Request.FormValue("memberId"); index != "" {
		data.MemberId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("memberMomId"); index != "" {
		data.MemberMomId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	data.MemberPhone = c.Request.FormValue("memberPhone")
	data.MemberName = c.Request.FormValue("memberName")

	data.PayType = c.Request.FormValue("payType")
	data.PayNo = c.Request.FormValue("payNo")
	data.PayTime = c.Request.FormValue("payTime")
	data.PayTimeStart = c.Request.FormValue("payTimeStart")
	data.PayTimeEnd = c.Request.FormValue("payTimeEnd")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	header := []string{"订单ID", "订单编号", "订单名称", "客户姓名", "客户账户", "所在地区", "小区", "机构品牌",
		"机构名称", "课程名称", "订单金额", "支付方式", "支付时间", "支付", "社区达人", "订单状态"} //标题
	cellist := [][]string{
		header,
	}
	cellist = DataToStringV4(result, cellist)

	page := count/pageSize + 1

	for i := 2; i <= page; i++ {
		pageIndex = i
		result, _, _ = data.GetPage(pageSize, pageIndex)
		if len(result) <= 0 {
			break
		}
		cellist = DataToStringV4(result, cellist)
	}

	// 创建文件
	filepath := "static/"
	filename := "Teacher_" + time.Now().Format("20060102150405") + ".csv"
	newFile, err := os.Create(filepath + filename)
	if err != nil {
		app.OK(c, nil, err.Error())
		return
	}
	defer func() {
		newFile.Close()

		err := os.Remove(filepath + filename)
		if err != nil {
			// 删除失败
			lognew.Info(c, "导出文件-清理失败", lognew.Fields{"file": filepath + filename, "err": err.Error()})
		}

	}()

	// 写入UTF-8
	newFile.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM，防止中文乱码
	// 写数据到csv文件
	w := csv.NewWriter(newFile)
	// WriteAll方法使用Write方法向w写入多条记录，并在最后调用Flush方法清空缓存。
	w.WriteAll(cellist)
	w.Flush()

	c.File(filepath + filename)

}

// OrganTeacher
// "订单ID",  "订单编号","订单名称","客户姓名","客户账户","所在地区", "小区", "机构品牌", "机构名称","课程名称","订单金额","支付方式","支付时间","支付","社区达人",”订单状态“
func DataToStringV4(list []models.Order, data [][]string) [][]string {
	for i := 0; i < len(list); i++ {
		op := fmt.Sprintf(".2f", list[i].OrderPrice)
		context := []string{
			strconv.Itoa(list[i].OrderId),
			list[i].OrderNo,
			list[i].OrderName,
			list[i].MemberName,
			list[i].MemberPhone,
			list[i].OrganName,
			list[i].OrganName,
			list[i].BrandName,
			list[i].OrganName,
			list[i].CourseName,
			op,
			list[i].PayType,
			list[i].PayTime,
			list[i].PayNo,
			strconv.Itoa(list[i].MemberMomId),
			list[i].MemberMomName,
			list[i].UpdatedAt.Format("2006-01-02 15:04:05"),
			list[i].OrderStatus,
		}
		data = append(data, context)
	}
	return data
}

func GetOrderList(c *gin.Context) {
	var data models.Order
	var err error
	var pageSize = 10
	var pageIndex = 1

	if size := c.Request.FormValue("pageSize"); size != "" {
		pageSize = tools.StrToInt(err, size)
	}
	if index := c.Request.FormValue("pageIndex"); index != "" {
		pageIndex = tools.StrToInt(err, index)
	}

	data.OrderNo = c.Request.FormValue("orderNo")
	data.OrderName = c.Request.FormValue("orderName")
	data.OrderStatus = c.Request.FormValue("orderStatus")

	if index := c.Request.FormValue("memberId"); index != "" {
		data.MemberId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("memberMomId"); index != "" {
		data.MemberMomId = tools.StrToInt(err, index)
	}
	if index := c.Request.FormValue("courseId"); index != "" {
		data.CourseId = tools.StrToInt(err, index)
	}
	data.MemberPhone = c.Request.FormValue("memberPhone")
	data.MemberName = c.Request.FormValue("memberName")

	data.PayType = c.Request.FormValue("payType")
	data.PayNo = c.Request.FormValue("payNo")
	data.PayTime = c.Request.FormValue("payTime")

	data.AddressSearch = c.Request.FormValue("addressSearch") //所在地区
	data.Address = c.Request.FormValue("address")             //小区名称
	data.OrganName = c.Request.FormValue("organName")         //机构名称
	data.BrandName = c.Request.FormValue("brandName")         //品牌名称

	data.PayTimeStart = c.Request.FormValue("payTimeStart")
	data.PayTimeEnd = c.Request.FormValue("payTimeEnd")

	data.DataScope = tools.GetUserIdStr(c)
	result, count, err := data.GetPage(pageSize, pageIndex)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.PageOK(c, result, count, pageIndex, pageSize, "")
}

func GetOrder(c *gin.Context) {
	var data models.Order
	data.OrderId, _ = tools.StringToInt(c.Param("id"))
	result, err := data.Get()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	res := make(map[string]interface{})
	res["order_info"] = result
	var Member models.Member
	Member.MemberId = result.MemberId
	res["member"], _ = Member.Get()
	var orderPay models.OrderPay
	orderPay.OrderId = data.OrderId
	res["order_pay"] = orderPay.GetList()
	var orderShare models.OrderShare
	orderShare.OrderId = data.OrderId
	res["order_share"] = orderShare.GetListV2()
	var orderStudent models.OrderStudent
	orderStudent.OrderId = data.OrderId
	res["order_student"] = orderStudent.GetList()
	var courseIn models.OrderCourse
	courseIn.OrderId = data.OrderId
	res["order_course"] = courseIn.GetList()
	var organ models.Organ
	res["organ_info"], _ = organ.GetByID(result.OrganId)
	var refund models.OrderRefund
	refund.OrderId = data.OrderId
	res["order_refund"], _ = refund.GetList()

	var orderLog models.OrderOprateLog
	orderLog.OrderId = data.OrderId
	res["order_log"] = orderLog.GetList()

	app.OK(c, res, "")
}

func CloseOrder(c *gin.Context) {
	var data models.Order

	uid := tools.GetUserId(c)
	uName := tools.GetUserName(c)

	var cc models.OrderClose
	err := c.ShouldBindJSON(&cc)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	data.OrderId = cc.OrderId
	result, err := data.Get()
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	if result.OrderStatus == constant.ORDER_STATUS_90 {
		app.CommonResp(c, 0, "当前订单已经关闭", result)
		return
	}
	cc.OrderStatus = constant.ORDER_STATUS_90
	re, er := result.Close(result.OrderId, cc)
	if er != nil {
		app.CommonResp(c, 0, "订单关闭失败"+er.Error(), re)
		return
	}

	//用户操作订单记录
	orlog := models.OrderOprateLog{
		OrderId:         result.OrderId,
		Title:           "订单关闭",
		Desc:            "订单关闭/操作人：" + uName,
		LogType:         "1",
		OrderStatusName: tools.OrderStatusName(result.OrderStatus),
		PayStatusName:   tools.PayStatusName(result.PayTime, result.RefundTime),
		LogName:         "订单关闭",
		LogUid:          uid,
	}
	_, _ = orlog.Create() // 订单关闭

	app.OK(c, re, "订单关闭成功")
}
func InsertOrder(c *gin.Context) {
	var data models.Order
	err := c.ShouldBindJSON(&data)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	result, err := data.Create()
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func UpdateOrder(c *gin.Context) {
	var data models.Order
	err := c.BindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	result, err := data.Update(data.OrderId)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func DeleteOrder(c *gin.Context) {
	var data models.Order

	IDS := tools.IdsStrToIdsIntGroup("id", c)
	_, err := data.BatchDelete(IDS)
	if err != nil {
		app.ApiResp(c, -1, "数据删除失败："+err.Error(), nil)
		return
	}

	app.OK(c, nil, msg.DeletedSuccess)
}
